package cn.cocho.custom.yunCashierDf.interceptor;

import cn.cocho.common.web.app.JsonResultContants;
import cn.cocho.common.web.utils.JsonResult;
import cn.cocho.custom.yunCashierDf.cache.CacheCtrl;
import cn.cocho.custom.yunCashierDf.utils.AppConstants;
import cn.cocho.custom.yunCashierDf.utils.AppContexts;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * Created by WQJ on 2016-06-23.
 */
public class MemberInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    CacheCtrl cacheCtrl;

    /**
     * 拦截处理
     *
     * @param request  请求信息
     * @param response 响应信息
     * @param handler  代理
     * @return false：未通过拦截器，不再继续往下走，true：通过了拦截器，将会继续往下走
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String token = request.getParameter("token");
        if (null == token || !cacheCtrl.getTokenCtrl().checkTokenTimeOutAndInitThreadLocal(token)) {// 未登录或Token过期
            PrintWriter out = response.getWriter();
            String jsonString = JSON.toJSONString(new JsonResult(JsonResultContants.TOKEN_TIME_OUT, JsonResultContants.TOKEN_TIME_OUT_MSG));
            out.print(jsonString);
            out.flush();
            out.close();
            return false;
        } else {
            cacheCtrl.getCurrentUcUserInfo();
            if (!"MEMBERS".equals(AppContexts.getRoles()) && !AppConstants.ROLES_ROOT.equals(AppContexts.getRoles()) && !AppConstants.ROLES_ADMIN.equals(AppContexts.getRoles())) {//如果当前用户不是MEMBERS角色的用户
                PrintWriter out = response.getWriter();
                String jsonString = JSON.toJSONString(new JsonResult(JsonResultContants.INTERCEPTORED, "你的角色不是商户，无权进行该操作！"));
                out.print(jsonString);
                out.flush();
                out.close();
                return false;
            }
            return super.preHandle(request, response, handler);
        }
//        return true;//也可以使用返回true通过本次拦截
    }
}
